package com.liuzh.fitnessplan.activity

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.liuzh.fitnessplan.R
import com.liuzh.fitnessplan.base.BaseActivity
import com.liuzh.fitnessplan.database.bean.TimePlans
import com.liuzh.fitnessplan.databinding.ActivityPlansAddBinding
import com.liuzh.fitnessplan.tools.AppDataInfo
import com.liuzh.fitnessplan.tools.RoomDatabaseUtil
import kotlinx.android.synthetic.main.activity_plans_add.*
import org.json.JSONObject
import java.util.*
import kotlin.math.min

class PlansFactorActivity() : BaseActivity() {
    private lateinit var bind : ActivityPlansAddBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bind = ActivityPlansAddBinding.inflate(layoutInflater)
        setContentView(bind.root)

        when(intent.getBooleanExtra("isAdd",false)){
            false -> updateSQLData()
            true -> addSQLData()
        }
    }

    private fun updateSQLData() {
        val id = intent.getIntExtra("id",0)
        val database = RoomDatabaseUtil.instance.getDatabase(this)
        val singleData = database.timeDao().getSingleData(id)
        bind.itemTitle.text = "项目：${singleData.project}"
        bind.editLabel.setText(singleData.title)
        when(singleData.repeat){
            "once" -> bind.plansBtnGroup.check(R.id.item_repeat_once)
            "everyday" -> bind.plansBtnGroup.check(R.id.item_repeat_everyday)
        }
        val jsonObject = JSONObject(singleData.date)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            time_pick.hour = jsonObject.getInt("hour")
            time_pick.minute = jsonObject.getInt("minute")
        }
        bind.btnSubmit.setOnClickListener {
            if(bind.editLabel.text.toString().isEmpty()){
                Toast.makeText(this,"标签不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val title = bind.editLabel.text.toString()
            val time = JSONObject()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                time.put("hour","${bind.timePick.hour}")
                time.put("minute","${bind.timePick.minute}")
                Log.d("time", "time = ${time.toString()}")
            }
            var repeat : String? = null
            when(bind.plansBtnGroup.checkedRadioButtonId){
                bind.itemRepeatOnce.id -> repeat = "once"
                bind.itemRepeatEveryday.id -> repeat = "everyday"
                else -> Log.d("RadioGroup","错误")
            }
            val timePlans = TimePlans(singleData.id,singleData.userId,time.toString(),singleData.project,title,singleData.isOpen,repeat!!)
            database.timeDao().update(timePlans)
            cancelAlarm(timePlans.id)
            addAlarm(timePlans.id,time)
            Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show()
            finish()
        }
    }


    private fun addSQLData() {
        val projectName = intent.getStringExtra("title")
        bind.itemTitle.text = "项目：$projectName"
        bind.btnSubmit.setOnClickListener {
            val userId = AppDataInfo.instance.getId(this)
            if(bind.editLabel.text.toString().isEmpty()){
                Toast.makeText(this,"标签不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val title = bind.editLabel.text.toString()
            //把时间转换成JSONObeject格式再转成String
            val time = JSONObject()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                time.put("hour","${bind.timePick.hour}")
                time.put("minute","${bind.timePick.minute}")
                Log.d("time", "time = ${time.toString()}")
            }
            var repeat : String? = null
            when(bind.plansBtnGroup.checkedRadioButtonId){
                bind.itemRepeatOnce.id -> repeat = "once"
                bind.itemRepeatEveryday.id -> repeat = "everyday"
                else -> Log.d("RadioGroup","错误")
            }
            val timePlans = TimePlans(0,userId,time.toString(),projectName!!,title,true,repeat!!)
            val db = RoomDatabaseUtil.instance.getDatabase(this).timeDao().addData(timePlans)
            val id = RoomDatabaseUtil.instance.getDatabase(this).timeDao().getId()
            addAlarm(id,time)
            Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    private fun addAlarm(id : Int,time : JSONObject){
        //计算目标时间
        val calendar = Calendar.getInstance()
        val hour : Int = time.getInt("hour")
        val minute : Int = time.getInt("minute")
        var tagHour : Int = if(calendar[Calendar.HOUR_OF_DAY] > hour){
            24 - (calendar[Calendar.HOUR_OF_DAY] - hour)
        }else{
            hour - calendar[Calendar.HOUR_OF_DAY]
        }
        var tagMinute : Int = if(calendar[Calendar.MINUTE] > minute){
            60 - (calendar[Calendar.MINUTE] - minute)
        }else{
            minute - calendar[Calendar.MINUTE]
        }

        //设置Alarm
        val intent = Intent("com.liuzh.ALARM_BROADCAST")
        intent.putExtra("id",id)
        val pendingIntent = PendingIntent.getBroadcast(this,id,intent,PendingIntent.FLAG_CANCEL_CURRENT)
        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.setExact(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+3600*1000*tagHour+60*1000*tagMinute,pendingIntent)
        Log.d("Alarm Info", " 添加闹钟定时器")
    }

    private fun cancelAlarm(id : Int){
        val intent = Intent("com.liuzh.ALARM_BROADCAST")
        //intent.putExtra("id",id)
        val pendingIntent = PendingIntent.getBroadcast(this,id,intent,
            PendingIntent.FLAG_CANCEL_CURRENT)
        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.cancel(pendingIntent)
    }
}